package com.zrx.app.android.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.VideoView;

import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.ZRXApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by liuji on 2017/4/14.
 *
 *
 * 获取视频独立的fragment
 */

public class VideoFrag extends BaseFragment {
    private static final String TAG = "VideoFrag";

    VideoView videoView = null;
    View takeVideo = null;
    View pickVideo = null;
    TextView label_keyName = null;
    TextView label_description = null;

    private String rawVideoPath;
    private String videoPath;

    @Override
    public void initParams(JSONObject node, String key, String dir) {
        super.initParams(node, key, dir);
        this.rawVideoPath = this.dir + "/" + key + ".raw.mp4";
        this.videoPath = this.dir + "/" + key + ".mp4";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View _view = inflater.inflate(R.layout.layout_video, container, false);
        try {
            label_keyName = (TextView) _view.findViewById(R.id.label_keyName);
            label_description = (TextView) _view.findViewById(R.id.label_description);
            videoView = (VideoView) _view.findViewById(R.id.view_video);
            takeVideo = _view.findViewById(R.id.btn_takeVideo);
            pickVideo = _view.findViewById(R.id.btn_pickVideo);

            label_keyName.setText(key);
            if (node.containsKey("policy"))
                label_description.setText(node.getJSONArray("policy").toJSONString());
            else
                label_description.setText("");
            loadVideo(videoView);


            videoView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (videoView.isPlaying())
                        videoView.pause();
                    else
                        videoView.start();
                    return false;
                }
            });

            takeVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(rawVideoPath)));
                    startActivityForResult(takeVideoIntent, ZRXUTIL.REQ_TAKE_VIDEO);
                }
            });


            pickVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("video/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "选择视频"), ZRXUTIL.REQ_LOCAL_VIDEO);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return _view;
    }

    class VideoAsyncTask extends AsyncTask {
        String fileId;

        @Override
        protected Object doInBackground(Object[] params) {
            fileId = (String) params[1];
            return RemoteConn.getInstance().getFile(fileId, ZRXUTIL.getCachePath() + "/" + fileId);
        }

        @Override
        protected void onPostExecute(Object o) {
            if (Boolean.TRUE.equals(o)) {
                videoView.setBackground(null);
                videoView.setVideoURI(Uri.fromFile(new File(ZRXUTIL.getCachePath() + "/" + fileId)));
            }
        }
    }

    ;

    private void loadVideo(VideoView iv) {
        final File videoFile = new File(videoPath);
        final File rawVideoFile = new File(rawVideoPath);

        if (videoFile.exists())
            videoView.setVideoURI(Uri.fromFile(videoFile));
        else if (rawVideoFile.exists())
            videoView.setVideoURI(Uri.fromFile(rawVideoFile));
        else if (node.containsKey("val")) {
            final String fileId = node.getString("val");
            File cacheFile = new File(ZRXUTIL.getCachePath() + "/" + fileId);
            if (cacheFile.exists()) {
                videoView.setBackground(null);
                videoView.setVideoURI(Uri.fromFile(cacheFile));
            } else {
                VideoAsyncTask vat = new VideoAsyncTask();
                videoView.setBackgroundResource(R.drawable.loading);
                vat.execute(AsyncTask.THREAD_POOL_EXECUTOR, fileId);
            }

        } else {
            videoView.setBackgroundResource(R.drawable.id_photo);
        }
    }

    public String getKey() {
        return key;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK)
            try {
                if (requestCode == ZRXUTIL.REQ_TAKE_VIDEO) {
                    new File(videoPath).delete();
                    //ZRXUTIL.compressVideo(prePath+".raw.mp4",prePath+".mp4");
                    new File(rawVideoPath).renameTo(new File(videoPath));
                    videoView.setBackground(null);
                    videoView.setVideoURI(null);
                    videoView.setVideoURI(Uri.fromFile(new File(videoPath)));
                    node.remove("val");
                } else if (requestCode == ZRXUTIL.REQ_LOCAL_VIDEO) {
                    new File(videoPath).delete();
                    InputStream is = ZRXApplication.getAppContext().getContentResolver().openInputStream(data.getData());
                    //BufferedInputStream bis=new BufferedInputStream(inputStream);
                    FileOutputStream os = new FileOutputStream(rawVideoPath);
                    ZRXUTIL.copyFile(is, os);
                    //ZRXUTIL.compressVideo(prePath+".raw.mp4",prePath+".mp4");
                    new File(rawVideoPath).renameTo(new File(videoPath));
                    //send request compression to service
                    videoView.setBackground(null);
                    videoView.setVideoURI(null);
                    videoView.setVideoURI(Uri.fromFile(new File(videoPath)));
                    node.remove("val");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


}
